package org.insia.smartposse.struts.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.insia.smartposse.config.DAOFactory;
import org.insia.smartposse.metier.Company;
import org.insia.smartposse.metier.Freelance;
import org.insia.smartposse.metier.User;
import org.insia.smartposse.utils.ActionUtils;
/**
 * Action for the login.
 * @author sok hout
 *
 */
public class LoginAction extends Action {

	protected final Logger log = Logger.getLogger(getClass());

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
    	log.info("LoginAction.execute");
		List<String> messages = new ArrayList<String>();
    	request.setAttribute("messages", messages);
	
		String login 	= ActionUtils.getString(request, "login","", messages, "welcome.error.login");
		String password = ActionUtils.getString(request, "password","", messages, "welcome.error.password");
		
		final User user = DAOFactory.getUserDAO().getUserByPasswordLogin(login, password);
		
		if (null == user) {
			return mapping.findForward("failure");
		} else {
			request.getSession().setAttribute("jsessionid", request.getRequestedSessionId());
			Freelance freelance = null;
			try {
				freelance = DAOFactory.getFreelanceDAO().get(user.getId());
			} catch (Exception e){}
			if (freelance != null) {
				request.getSession().setAttribute("freelance", freelance);
				request.getSession().setAttribute("user", freelance);
			} else {
				Company company = DAOFactory.getCompanyDAO().get(user.getId());
				request.getSession().setAttribute("company", company);
				request.getSession().setAttribute("user", company);
			}
			return mapping.findForward("success");
		}
    }
    
} 